import React, { useState } from 'react';
import { Button, Input, Card, Space, Typography, Divider } from 'antd';
import { useStreamMessage } from '@/hooks/use-stream-message';
import StreamText from '@/components/stream-text';

const { Title, Text } = Typography;

// 示例组件，展示如何使用流式消息功能
const StreamMessageExample: React.FC = () => {
  const [inputMessage, setInputMessage] = useState('');
  const [messages, setMessages] = useState<Array<{
    id: number;
    content: string;
    role: 'user' | 'assistant';
    isStreaming?: boolean;
  }>>([]);

  const { isStreaming, sendStreamMessage, error } = useStreamMessage({
    onStreamStart: () => {
      console.log('流式传输开始');
    },
    onMessageReceived: (content: string, isComplete: boolean) => {
      // 更新最后一条助手消息
      setMessages(prev => 
        prev.map((msg, index) => 
          index === prev.length - 1 && msg.role === 'assistant'
            ? { ...msg, content, isStreaming: !isComplete }
            : msg
        )
      );
    },
    onStreamEnd: () => {
      console.log('流式传输完成');
    },
    onError: (error) => {
      console.error('流式传输错误:', error);
    },
  });

  const handleSendMessage = async () => {
    if (!inputMessage.trim()) return;

    // 添加用户消息
    const userMessage = {
      id: Date.now(),
      content: inputMessage,
      role: 'user' as const,
    };

    // 添加空的助手消息占位符
    const assistantMessage = {
      id: Date.now() + 1,
      content: '',
      role: 'assistant' as const,
      isStreaming: true,
    };

    setMessages(prev => [...prev, userMessage, assistantMessage]);
    setInputMessage('');

    try {
      // 发送流式消息（这里使用模拟参数）
      await sendStreamMessage({
        authorization: 'demo-auth',
        chatId: 'demo-chat',
        sessionId: 'demo-session',
        message: inputMessage,
      });
    } catch (error) {
      console.error('发送消息失败:', error);
    }
  };

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <Title level={2}>EventStream 流式消息示例</Title>
      
      <Card title="聊天区域" className="mb-4">
        <div className="min-h-[400px] max-h-[400px] overflow-y-auto space-y-4">
          {messages.map((msg) => (
            <div
              key={msg.id}
              className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
            >
              <div
                className={`max-w-[70%] p-3 rounded-lg ${
                  msg.role === 'user'
                    ? 'bg-blue-500 text-white'
                    : 'bg-gray-100 text-gray-800'
                }`}
              >
                {msg.role === 'assistant' ? (
                  <StreamText
                    text={msg.content}
                    isStreaming={msg.isStreaming}
                    showCursor={true}
                  />
                ) : (
                  <Text className={msg.role === 'user' ? 'text-white' : ''}>
                    {msg.content}
                  </Text>
                )}
              </div>
            </div>
          ))}
          
          {messages.length === 0 && (
            <div className="text-center text-gray-500 py-20">
              <Text>开始对话吧！输入消息体验流式传输效果</Text>
            </div>
          )}
        </div>
      </Card>

      <Card title="发送消息">
        <Space.Compact style={{ width: '100%' }}>
          <Input
            value={inputMessage}
            onChange={(e) => setInputMessage(e.target.value)}
            placeholder="输入消息..."
            onPressEnter={handleSendMessage}
            disabled={isStreaming}
          />
          <Button 
            type="primary" 
            onClick={handleSendMessage}
            loading={isStreaming}
            disabled={!inputMessage.trim()}
          >
            {isStreaming ? '发送中...' : '发送'}
          </Button>
        </Space.Compact>
        
        {error && (
          <>
            <Divider />
            <Text type="danger">错误: {error.message}</Text>
          </>
        )}
      </Card>

      <Card title="功能说明" className="mt-4">
        <div className="space-y-2">
          <Text>• 实时流式数据接收和显示</Text>
          <br />
          <Text>• 动态光标效果指示正在接收数据</Text>
          <br />
          <Text>• 完整的错误处理机制</Text>
          <br />
          <Text>• 发送状态管理和防重复提交</Text>
          <br />
          <Text>• 响应式设计，支持移动端</Text>
        </div>
      </Card>
    </div>
  );
};

export default StreamMessageExample; 